/******************************************/
/******************************************/
/****  JS Document                     ****/
/****  by Andrew Mahon                 ****/
/****  amahon@gmail.com                ****/
/******************************************/
/******************************************/

(function(tc) {

  tc.jQ.fn.y5display = function(options){
    var $y5d = this, _o = {}, _components = {}, _newestFrameDisplayed = null, _oldestFrameDisplayed = null
    
    _o = tc.jQ.extend({
      
    },options)
    
    function _initialize(){
      tc.util.log('y5display._initialize')
      _setup_events()
      return $y5d
    }
    
    function _setup_events(){
      tc.util.log('y5display._setup_events')
      tc.events.bind('dataLoad',_dataLoadHandler)
      tc.events.bind('dataLoadError',_dataLoadErrorHandler)
    }
    
    function _dataLoadHandler(e,d){
      tc.util.log('y5display._dataLoadHandler')
      for(var i in d.data){
        if(d.data[i].url && d.data[i].timestamp){
          var _$img = tc.jQ("<img></img>")
          _$img.attr('src',d.data[i].url)
          if(d.data[i].timestamp <= _oldestFrameDisplayed || !_oldestFrameDisplayed){
            _oldestFrameDisplayed = d.data[i].timestamp
            $y5d.append(_$img)
            continue
          } 
          if (d.data[i].timestamp >= _newestFrameDisplayed || !_newestFrameDisplayed){
            _newestFrameDisplayed = d.data[i].timestamp
            $y5d.prepend(_$img)
            continue
          }
          
        }
      }
    }
    
    function _dataLoadErrorHandler(e,d){
      tc.util.log('y5display._dataLoadErrorHandler')
      $y5d.prepend('<p>DATA LOAD ERROR</p>')
    }
    
    return _initialize()
  }
})(tc);